// pages/personal/myorder/applyrefund/applyrefund.js
import { requestNote, uploadImg, createRefund } from '../../../../../config/config'
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: getApp().globalData.imgUrl,
    show: false,
    imgList: [],
    refundData: [],
    refundReason: [],
    refundNumber: '',
    refundAmount: 0,
    refundType: [],
    refundReasontext: '',
    contactsInputdata: '',
    refundPeopledata: '',
    refundPhonedata: '',
    servicePriceCouponAmount: '',
    orderParam: {},
    fileList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options) {
      let orderParam = JSON.parse(options.option)
      let returnType = orderParam.returnType
      if (returnType) {
        let refundReasontext = wx.getStorageSync('refundReason')
        if(refundReasontext) {
          this.setData({
            refundReasontext: refundReasontext
          })
        }
      } else {
        this.setData({
          refundReasontext: ''
        })
        wx.setStorageSync('refundReason', this.data.refundReasontext)
      }
      let refundReasonlist = app.globalData.getListvalue(app.globalData.valLsit, 'REFUND_REASON')
      let refundReason = []
      for(let i in refundReasonlist) {
        refundReason.push(refundReasonlist[i].name)
      }
      refundReason = refundReason.filter((item)=>{
         return item !== '卡券过期自动退' && item !== '拼购未成团自动退'
     })
      this.setData({
        orderParam: orderParam,
        refundReason: refundReason,
        refundReasonlist: refundReasonlist
      })
      if (orderParam.type) {
        let refundTypelist = app.globalData.getListvalue(app.globalData.valLsit, 'REFUND_TYPE')
        this.setData({
          refundType: this.filterByName(refundTypelist, orderParam.type),
        })
       }
      this.applyRefund()
    }
  },
  selectType() {
    let option = this.data.refundData
    wx.redirectTo({
      url: '../refundType/refundType?option=' +  JSON.stringify(option)
    })
  },
  // 上传凭证
  afterRead(event) {
    let that = this
    const file = event.detail.file
    let token = wx.getStorageSync('loginMsg')
    let header = {
      'content-type': 'application/json', // 默认值
      'token': token.token
    }
    var uploads = []
    for (var i = 0; i < file.length; i++) {
      let fileData = []
      fileData.push(file[i].path)
      uploads[i] = new Promise((resolve, reject) => {
        wx.uploadFile({
          url: uploadImg,
          filePath: file[i].path,
          name: 'file',
          formData:{
            'file': fileData
          },
          header: header,
          success: function (res) {
            let data = JSON.parse(res.data)
            let fileList = that.data.fileList
            fileList.push({ id: data.data[0].id, url: data.data[0].picturePath });
            that.setData({ 
              fileList: fileList
              });
            resolve(res)
          }
        })
      })
    }
    Promise.all(uploads).then((result) => {
      console.log('result',result)
    })
  },
  delImg(event) {
    let index = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(index,1);
    this.setData({
      fileList: fileList
    })
  },
  showRfund() {
    this.setData({
      show: true
    })
  },
  onCloseModel(e){  //关闭弹窗
    this.setData({
      show: false
    })
  },
  onConfirm(value, index) {
    let refundReasontext = value.detail.value
    this.setData({
      show: false,
      refundReasontext: refundReasontext
    })
    wx.setStorageSync('refundReason', refundReasontext)
  },
  onChange(picker, value, index) {
    // console.log('value',value,'index', index,'picker', picker);
  },
  onCancel() {
    this.setData({
      show: false
    })
    // Toast('取消');
  },
  moveHandle () {},
  // 输入联系人
  refundPeopleInput(e) {
    this.data.refundPeopledata = e.detail.value
    console.log('退款联系人', e.detail.value)
  },
  refundPhoneInput(e) {
    this.data.refundPhonedata = e.detail.value
  },
  refundAmountInputOnBlur(e) {
    let refundAmount = Number(this.data.refundAmount)
    let value = this.data.refundData.refundAmount
     if (refundAmount > value) {
      wx.showToast({
        title: '不能大于最多退款金额',
        icon: 'none',
        duration: 3000
      })
      this.setData({
        refundAmount: value
      })
    }
  },
  refundAmountInput(e) {
    let value = e.detail.value
    value = value.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
    this.setData({
      refundAmount: value
    })
  },
  contactsInput(e) {
    this.data.contactsInputdata = e.detail.value
  },
  // 退款数量减
  reduceRefundNumber(){
    let refundNumber
    if (this.data.refundNumber > 1) {
      refundNumber = this.data.refundNumber - 1
    } else {
      refundNumber = 1
    }
    this.setData({
     refundNumber: refundNumber
    })
  },
   // 退款数量加
   addRefundNumber(){
     let refundData = this.data.refundData
     let refundNumber = this.data.refundNumber
     if (refundNumber < refundData.productQuantity) {
       refundNumber = refundNumber + 1
       this.setData({
        refundNumber: refundNumber
       })
     } else {
       return
     }
   },
  //  申请退款查询
   applyRefund() {
    let that = this
    let paramesData = {}
    paramesData.orderId = that.data.orderParam.orderId
    paramesData.orderItemId = that.data.orderParam.orderItemId
    app.reqFun.requestJson('POST',requestNote,paramesData,(res)=>{
      if(res.data.success==1){
        let data = res.data.data
        // data.productAttr = JSON.parse(data.productAttr)
        that.setData({
          refundData: data,
          refundPeopledata: data.refundPeople,
          refundPhonedata: data.refundPhone,
          servicePriceCouponAmount: data.servicePriceCouponAmount,
          refundAmount: data.refundAmount,
          refundNumber: data.productQuantity,
          // refundReasontext: ''
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  // 保存申请退款
  saveRefund() {
    let that = this
    if(!that.data.refundReasontext) {
      wx.showToast({
        title: '请选择退款原因',
        icon: 'none',
        duration: 2000
      })
    } else if(that.data.refundType.length == 0 && that.data.refundData.deliveryType !== 'noLogistics') {
      wx.showToast({
        title: '请选择退款类型',
        icon: 'none',
        duration: 2000
      })
    } else if(!that.data.refundPeopledata) {
      wx.showToast({
        title: '请填写退款联系人',
        icon: 'none',
        duration: 2000
      })
    } else if(!that.data.refundPhonedata) {
      wx.showToast({
        title: '请填写退款联系电话',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.saveRefundqre()
    }
  },
  saveRefundqre() {
    let that = this
    let fileList = that.data.fileList
    let pictureList = []
    for(var i = 0, len = fileList.length; i < len; i++) {
      pictureList.push({pictureId: fileList[i].id})
    }
    let refundReasonlist = that.data.refundReasonlist
    let refundReason = refundReasonlist.filter(item => item.name == that.data.refundReasontext)
    console.log('refundReason', refundReason)
    let refundType = ''
    if (that.data.refundData.deliveryType !== 'noLogistics') {
      refundType = that.data.refundType[0].val
    } else {
      refundType = 'refund_only'
    }
    let paramesData = {
      "orderId": that.data.refundData.orderId,
      "orderItemId": that.data.refundData.orderItemId,
      "pictureList": pictureList,
      "refundAmount": that.data.refundAmount,
      "refundNote": that.data.contactsInputdata,
      "refundPeople": that.data.refundPeopledata,
      "refundPhone": that.data.refundPhonedata,
      "refundQuantity": that.data.refundNumber,
      "refundReason": refundReason[0].val,
      "refundType": refundType,
      "serviceAmount": that.data.servicePriceCouponAmount
    }
    console.log('paramesData', paramesData)
    app.reqFun.requestJson('POST',createRefund,paramesData,(res)=>{
      if(res.data.success==1){
        wx.redirectTo({
          url: '../returnRefund/returnRefund'
        })
      }
    })
  },
  filterByName(aim, name) {
    return aim.filter(item => item.val == name)
  },
  goreBack(e){
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})